package com.chookss.home.gallery;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.CityEntity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.CityEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.Nullable;

public class GalleryChoiceCityActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.rcLeft)
    RecyclerView rcLeft;
    @BindView(R.id.rcRight)
    RecyclerView rcRight;
    private CityLeftAdapter leftAdapter;
    private CityRightAdapter rightAdapter;
    private List<CityEntity> leftList = new ArrayList<>();
    private List<CityEntity.ChildListBean> rightList = new ArrayList<>();
    private int index = 0;
    private ArrayList<CityEntity.ChildListBean> lists = new ArrayList<>();
    private FlowAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_grallery_choice_city);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("地点");
        commonRightTxt.setText("保存");
        commonRightTxt.setVisibility(View.VISIBLE);
        Bundle bundle = getIntent().getExtras();
        ArrayList cityList = bundle.getParcelableArrayList("cityLists");
        lists = (ArrayList<CityEntity.ChildListBean>) cityList.get(0);
        commonRightTxt.setTextColor(getResources().getColor(R.color.main_color));
        rcLeft.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        leftAdapter = new CityLeftAdapter(R.layout.item_gallery_choice_city_left, this, leftList);
        rcLeft.setAdapter(leftAdapter);
        ((SimpleItemAnimator) rcLeft.getItemAnimator()).setSupportsChangeAnimations(false);
        rcRight.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        rightAdapter = new CityRightAdapter(R.layout.item_gallery_choice_city_right, this, rightList);
        rcRight.setAdapter(rightAdapter);
        ((SimpleItemAnimator) rcLeft.getItemAnimator()).setSupportsChangeAnimations(false);
        getData();
    }

    private void getData() {
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<CityEntity>>>() {
        }.getType(), null, Urls.getAddressTree, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<CityEntity>>() {
            @Override
            public void onSuccess(List<CityEntity> data) {
                dismissLoading();
                leftList.addAll(data);
                leftAdapter.notifyDataSetChanged();
                rightList.addAll(leftList.get(0).getChildList());
                rightAdapter.notifyDataSetChanged();
                if(lists.size()>0){
                    for (int i = 0; i < leftList.size(); i++) {
                        for (int j = 0; j <leftList.get(i).getChildList().size() ; j++) {
                            for (int k = 0; k <lists.size() ; k++) {
                                if(lists.get(k).getCode().equals(leftList.get(i).getChildList().get(j).getCode())){
                                    index=i;
                                    leftList.get(i).getChildList().get(j).setSelect(true);
                                    leftList.get(i).setSelect(true);
                                    leftAdapter.notifyItemChanged(i);
                                    if(leftList.get(i).getChildList().get(j).getIndex_parent()==0){
                                        leftAdapter.notifyItemChanged(0);
                                    }
                                    rightList.clear();
                                    rightList.addAll(leftList.get(i).getChildList());
                                    rightAdapter.notifyItemChanged(j);
                                    addCity(lists.get(k));
                                }
                            }
                        }
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<CityEntity.ChildListBean> mContentList;

        public FlowAdapter(Context mContext, List<CityEntity.ChildListBean> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_gallery_choice_city_title, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            mlp.setMargins(0, 0, Utils.dip2px(mContext, 12), Utils.dip2px(mContext, 12));
            view.setLayoutParams(mlp);

            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position).getName());
            holder.llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    removeCity(lists.get(position));
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            LinearLayout llDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                llDelete = itemView.findViewById(R.id.llDelete);
            }
        }
    }

    private void addCity(CityEntity.ChildListBean data) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).getName().equals(data.getName())) {
                lists.remove(i);
                i--;
            }
        }
        if (lists.size() == 0) {
            lists.add(data);
        } else {
            lists.add(0, data);
        }
        if (index == 0 && data.getIndex() == 0) {
            //选择是全国，去除当前选择的其他地市
            for (int i = 0; i < lists.size(); i++) {
                if (!lists.get(i).getName().equals(data.getName())) {

                    leftList.get(lists.get(i).getIndex_parent()).getChildList().get(lists.get(i).getIndex()).setSelect(false);
                    leftList.get(data.getIndex_parent()).setSelect(false);
                    KLog.i("-----" + leftList.get(data.getIndex_parent()).getName() + "==" + leftList.get(data.getIndex_parent()).isSelect());
                    leftAdapter.notifyItemChanged(lists.get(i).getIndex_parent());
                    lists.remove(i);
                    i--;
                }
            }
        } else if (data.getIndex() == 0) {
            //选择是全省，去除当前省选择的其他地市
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getIndex_parent() == 0) {
                    //去除全国
                    leftList.get(0).setSelect(false);
                    leftList.get(0).getChildList().get(0).setSelect(false);
                    leftAdapter.notifyItemChanged(0);
                    lists.remove(i);
                    i--;
                }
                if (lists.get(i).getParentCode().equals(data.getParentCode()) && !lists.get(i).getName().equals(data.getName())) {
                    rightList.get(lists.get(i).getIndex()).setSelect(false);
                    rightAdapter.notifyItemChanged(lists.get(i).getIndex());
                    lists.remove(i);
                    i--;
                }
            }
        } else {
            //选择的普通地级市 取消第一条数据全省的选择
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getIndex_parent() == 0) {
                    //去除全国
                    leftList.get(0).setSelect(false);
                    leftList.get(0).getChildList().get(0).setSelect(false);
                    leftAdapter.notifyItemChanged(0);
                    lists.remove(i);
                    i--;
                }
                if (lists.get(i).getParentCode().equals(data.getParentCode()) && lists.get(i).getIndex() == 0) {
                    rightList.get(0).setSelect(false);
                    rightAdapter.notifyItemChanged(0);
                    lists.remove(i);
                    i--;
                }
            }
        }
        if (lists.size() > 4) {
            removeCity(lists.get(4));
        } else {
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
            tvNum.setText(lists.size() + "/4");
        }

    }

    private void removeCity(CityEntity.ChildListBean data) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).getName().equals(data.getName())) {
                if (data.getIndex_parent() == index) {
                    //在当前省市下
                    leftList.get(data.getIndex_parent()).setSelect(false);
                    rightList.get(data.getIndex()).setSelect(false);
                    for (int j = 0; j < rightList.size(); j++) {
                        if (rightList.get(j).isSelect()) {
                            leftList.get(data.getIndex_parent()).setSelect(true);
                        }
                    }
                    leftAdapter.notifyItemChanged(data.getIndex_parent());
                    rightAdapter.notifyItemChanged(data.getIndex());
                } else {
                    //不在当前省市下
                    leftList.get(data.getIndex_parent()).setSelect(false);
                    leftList.get(data.getIndex_parent()).getChildList().get(data.getIndex()).setSelect(false);
                    for (int y = 0; y < leftList.get(data.getIndex_parent()).getChildList().size(); y++) {
                        if (leftList.get(data.getIndex_parent()).getChildList().get(y).isSelect()) {
                            leftList.get(data.getIndex_parent()).setSelect(true);
                        }
                    }
                    leftAdapter.notifyItemChanged(data.getIndex_parent());
                }
                lists.remove(i);
                i--;
            }
        }

        // 设置 Adapter
        if (lists.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
        } else {
            flowLayout.setVisibility(View.GONE);
        }
        tvNum.setText(lists.size() + "/4");
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if (lists.size() == 0) {
                    //
                    MyToast.show("请选择至少一个城市");
                } else {
                    EventBus.getDefault().post(new CityEvent(lists));
                    finish();
                }
                break;
        }
    }

    class CityLeftAdapter extends BaseQuickAdapter<CityEntity, BaseViewHolderEx> {
        private Context context;

        public CityLeftAdapter(int layoutResId, Context context, @Nullable List<CityEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, CityEntity item) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            LinearLayout llBg = helper.getView(R.id.llBg);
            tvTitle.setText(item.getName());
            if (index == helper.getItemPosition()) {
                llBg.setBackgroundColor(getResources().getColor(R.color.main_bg));
                tvTitle.setTextColor(getResources().getColor(R.color.main_color));
            } else {
                llBg.setBackgroundColor(getResources().getColor(R.color.white));
                if (item.isSelect()) {
                    tvTitle.setTextColor(getResources().getColor(R.color.main_color));
                } else {
                    tvTitle.setTextColor(getResources().getColor(R.color.text_gray3));
                }
            }

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (index != helper.getItemPosition()) {
                        leftAdapter.notifyItemChanged(index);
                        index = helper.getItemPosition();
                        leftAdapter.notifyItemChanged(index);
                        rightList.clear();
                        rightList.addAll(leftList.get(helper.getItemPosition()).getChildList());
                        rightAdapter.notifyDataSetChanged();
                    }

                }
            });
        }
    }

    class CityRightAdapter extends BaseQuickAdapter<CityEntity.ChildListBean, BaseViewHolderEx> {
        private Context context;

        public CityRightAdapter(int layoutResId, Context context, @Nullable List<CityEntity.ChildListBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, CityEntity.ChildListBean item) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            ImageView ivChoice = helper.getView(R.id.ivChoice);
            tvTitle.setText(item.getName());
            if (item.isSelect()) {
                tvTitle.setTextColor(getResources().getColor(R.color.main_color));
                ivChoice.setVisibility(View.VISIBLE);
            } else {
                tvTitle.setTextColor(getResources().getColor(R.color.text_gray3));
                ivChoice.setVisibility(View.GONE);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isSelect()) {
                        removeCity(item);
                        item.setSelect(false);
                        leftList.get(index).setSelect(false);
                        for (int i = 0; i < rightList.size(); i++) {
                            if (rightList.get(i).isSelect()) {
                                leftList.get(index).setSelect(true);
                            }
                        }
                    } else {
                        item.setSelect(true);
                        leftList.get(index).setSelect(true);
                        item.setIndex(helper.getItemPosition());
                        item.setIndex_parent(index);
                        addCity(item);
                    }
                    rightAdapter.notifyItemChanged(helper.getItemPosition());
                }
            });
        }
    }
}
